package com.cnctema.easecalendar_weekly_view

import android.content.Intent
import android.graphics.Typeface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.viewpager.widget.ViewPager
import com.cnctema.easecalendar_weekly_view.activities.AboutMe
import com.cnctema.easecalendar_weekly_view.activities.AddEventActivity
import com.cnctema.easecalendar_weekly_view.adapters.WeekPagerAdapter
import com.cnctema.easecalendar_weekly_view.database.Config
import com.cnctema.easecalendar_weekly_view.databinding.ActivityMainBinding
import com.cnctema.easecalendar_weekly_view.extensions.config
import com.cnctema.easecalendar_weekly_view.extensions.seconds
import com.cnctema.easecalendar_weekly_view.fragments.WeekFragment
import com.cnctema.easecalendar_weekly_view.utils.FormatterUtils
import com.cnctema.easecalendar_weekly_view.views.MyScrollView
import org.joda.time.DateTime

class MainActivity : AppCompatActivity() {
    private val PREFILLED_WEEKS = 53

    private lateinit var binding : ActivityMainBinding
    private lateinit var config: Config

    companion object {
        var mWeekScrollY = 0
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
        config = applicationContext.config

        mWeekScrollY = resources.getDimension(R.dimen.weekly_view_row_height).toInt()* DateTime().hourOfDay //移动到当前时间 or 默认工作开始时间

        fillWeeklyViewPager()   //填充viewpager
        fillTimeLatter()    //填充时间轴
    }

    //填充日程视图viewpager
    private fun fillWeeklyViewPager(){
        // thisweek 本周星期x(firstDayIndex)距离1970年1月1日的秒数
        val weekTSs = getWeekTimestamps()
        val weeklyAdapter = WeekPagerAdapter(supportFragmentManager, weekTSs, object : WeekFragment.WeekScrollListener {
            override fun scrollTo(y: Int) {
                binding.weekViewHoursScrollview.scrollY = y
                mWeekScrollY = y
            }
        })

        binding.weekViewViewPager.apply {
            adapter = weeklyAdapter
            addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
                override fun onPageScrollStateChanged(state: Int) {}
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

                override fun onPageSelected(position: Int) {
                    setupActionbarTitle(weekTSs[position])
                }
            })
            currentItem = weekTSs.size / 2
        }

        binding.weekViewHoursScrollview.setOnScrollviewListener(object : MyScrollView.ScrollViewListener {
            override fun onScrollChanged(scrollView: MyScrollView, x: Int, y: Int, oldx: Int, oldy: Int) {
                mWeekScrollY = y
                weeklyAdapter.updateScrollY(binding.weekViewViewPager.currentItem, y)
            }
        })
    }

    //填充时间轴
    private fun fillTimeLatter(){
        // 填充时间栏
        binding.weekViewHoursHolder.removeAllViews()
        for (i in 1..23) {
            val view = layoutInflater.inflate(R.layout.item_weekly_view_hour_textview, null, false) as TextView
            val value = i.toString()
            view.apply {
                text = if (value.length == 2) value else "0$value"
                if(DateTime().hourOfDay == i){
                    setTextColor( ContextCompat.getColor(context,R.color.colorAccent))
                    typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                }
            }
            binding.weekViewHoursHolder.addView(view)
        }
    }

    // 获取周时间戳数组
    private fun getWeekTimestamps(): List<Long> {
        val dayInCalendar =config.dayInCalendar
        val dateTime = if (dayInCalendar == 7){
            DateTime().withDayOfWeek(1).withTime(0, 0, 0, 0)
        }else{
            DateTime().withTime(0, 0, 0, 0)
        }

        var currWeek = if(dayInCalendar == 7){
            dateTime.minusWeeks(PREFILLED_WEEKS / 2)
        }else{
            dateTime.minusDays(PREFILLED_WEEKS*dayInCalendar/2-(dayInCalendar/2))
        }

        val weekTSs = ArrayList<Long>(PREFILLED_WEEKS)
        for (i in 0 until PREFILLED_WEEKS){
            weekTSs.add(currWeek.seconds())
            currWeek = currWeek.plusDays(dayInCalendar)
        }
        return weekTSs
    }

    // 设置活动页面标题
    private fun setupActionbarTitle(timestamp: Long) {
        val startDateTime = FormatterUtils.getDateTimeFromTS(timestamp)     //开始边界时间
        val endDateTime = FormatterUtils.getDateTimeFromTS(timestamp + WEEK_SECONDS)        //结束边界时间
        val startMonthName = FormatterUtils.getMonthName(applicationContext, startDateTime.monthOfYear)   //开始月份

        //设置大标题
        if (startDateTime.monthOfYear == endDateTime.monthOfYear) {
            var newTitle = startMonthName
            if (startDateTime.year != DateTime().year)
                newTitle += " - ${startDateTime.year}"
            this.title = newTitle
        } else {
            val endMonthName = FormatterUtils.getMonthName(applicationContext, endDateTime.monthOfYear)
            this.title = "$startMonthName - $endMonthName"        //设置大标题
        }

        //设置小标题
        this.supportActionBar?.subtitle = String.format(getString(R.string.week),startDateTime.plusDays(3).weekOfWeekyear)

    }

    // 设置标题栏菜单
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    //指派menu事件
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.main_add_event->{
                Intent(applicationContext, AddEventActivity::class.java).apply { //点击修改
                    putExtra(EVENT_ID,-1L)
                    startActivity(this)
                }
                true
            }
            R.id.main_resetCalendarView_dayly -> {  //日视图
                if(config.dayInCalendar == 1){ return true}
                config.dayInCalendar = 1
                fillWeeklyViewPager()
                true
            }
            R.id.main_resetCalendarView_weekly ->{  //周视图
                if(config.dayInCalendar == 7){ return true}
                config.dayInCalendar = 7
                fillWeeklyViewPager()
                true
            }
            R.id.main_resetCalendarView_nDay ->{   //自定义天数
                showNDaySelectDialog(config.dayInCalendar){
                    fillWeeklyViewPager()
                }
                true
            }
            R.id.main_about ->{   //自定义天数
                Intent(applicationContext, AboutMe::class.java).apply { startActivity(this) }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }


    //自定义视图天数
    private fun showNDaySelectDialog(currSelect:Int,callback:()->Unit){
        val view = layoutInflater.inflate(R.layout.dialog_main_set_ndayview,null)
        val textView = view.findViewById<TextView>(R.id.tv_selected_nDay)
        val seekBar = view.findViewById<SeekBar>(R.id.sb_select_nDay)

        textView.text = "当前选择:${currSelect}天"
        seekBar.progress = currSelect-1
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                textView.text = "当前选择:${progress+1}天"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        //弹出对话框
        AlertDialog.Builder(this@MainActivity)
            .setView(view).setTitle("自定义天数")
            .setPositiveButton("确认"){ dialog, which ->
                if(seekBar.progress+1 != currSelect){
                    config.dayInCalendar = seekBar.progress+1
                    callback.invoke()
                }
            }
            .setNegativeButton("取消"){_, _ ->}   //do nothing
            .create().show()
    }

}
